<template>
    <div>
        <el-form label-width="140" :model="form" class="demo-form-inline">
            <el-form-item label="任务选择:">{{ state.form.taskName }} </el-form-item>
            <el-form-item label="任务计划时间范围:" label-width="200">
                <!--        {{ state.form.planStartTime }}至{{ state.form.planEndTime }}-->
                {{getTime()}}
            </el-form-item>
            <el-form-item label="任务主责部门:">
                {{ state.form.responsibleDepartmentName }}
            </el-form-item>
            <el-form-item label="任务责任人:">
                {{ state.form.responsibleUserName }}
            </el-form-item>
        </el-form>
        <div>
            <tableIndex
                :tableData="state.tableData"
                :tableHead="tableHead"
                :isIndex="true"
                :isSelection="true"
                :isRadio="true"
                :isPaging="false"
                :notSearch="true"
                :fields="state.fields"
                :height="600"
                :page="state.page"
                @selectChange="selectChange"
            >
                <template #btns>
                    <el-button
                        size="small"
                        class="button_edit"
                        type="primary"
                        @click="projectProposal()"
                    >新增</el-button
                    >
                    <el-button
                        size="small"
                        class="button_edit"
                        type="primary"
                        @click="deleteHandler()"
                    >删除</el-button
                    >
                    <el-button
                        size="small"
                        class="button_edit"
                        type="primary"
                        @click="upAllHandler()"
                    >上移</el-button
                    >
                    <el-button
                        size="small"
                        class="button_edit"
                        type="primary"
                        @click="downAllHandler()"
                    >下移</el-button
                    >
                </template>
            </tableIndex>
            <div>共{{state.tableData.length||0}}项任务</div>
<!--            <div style="text-align: right">
                <el-button type="primary" @click="saveConfigHandler" class="button_edit">保存配置</el-button>
            </div>-->
        </div>

        <el-dialog
            v-model="state.centerDialogVisible"
            title="实施任务节点"
            width="30%"
            class="dialog dialogStyle"
            align-center
            @open="openDialog"
            @close="closeDialog"

        >
            <el-form
                ref="formRef"
                :model="formInline"
                :rules="rules"
                label-width="230"
            >
                <el-form-item label="所属任务名称">
                    <el-input disabled v-model="state.form.taskName" placeholder="" />
                </el-form-item>
                <el-form-item label="任务节点(工作细项)名称" prop="itemName">
                    <el-input v-model="formInline.itemName" placeholder="" />
                </el-form-item>
                <el-form-item label="责任部门">
                    <el-input
                        disabled
                        v-model="state.form.responsibleDepartmentName"
                        placeholder=""
                    />
                </el-form-item>
                <el-form-item label="责任人" prop="responsibleUserId">
                    <el-select v-model="formInline.responsibleUserId" placeholder="" disabled>
                        <el-option
                            v-for="item in state.projectTendersWayList"
                            :key="item.userId"
                            :label="item.userName"
                            :value="item.userId"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="节点实施行为" prop="actionId">
                    <el-select v-model="formInline.actionId" placeholder="">
                        <el-option
                            v-for="item in state.implementationBehavior"
                            :key="item.actionId"
                            :label="item.actionName"
                            :value="item.actionId"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="节点计划实施期限" prop="planStartTime">
                    <el-date-picker
                        v-model="formInline.planStartTime"
                        type="daterange"
                        range-separator="-"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
                        value-format="YYYY-MM-DD HH:mm:ss"
                    />
                </el-form-item>
                <el-form-item label="督办人" prop="superviseUserId">
                    <el-select v-model="formInline.superviseUserId" placeholder="">
                        <el-option
                            v-for="item in state.projectTendersWayList"
                            :key="item.userId"
                            :label="item.userName"
                            :value="item.userId"
                        />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
        <span class="dialog-footer">
          <el-button @click="state.centerDialogVisible = false" class="button_cancel2">取消</el-button>
          <el-button @click="submitFormInline" class="button_view"> 确定 </el-button>
        </span>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import { ref, reactive, onMounted, onBeforeMount } from 'vue'
import { getURLhandler } from '@/views/constructionProjectManage/static/utools.js'
import {darkLine, department} from '@/api/project'
import { ElForm, ElFormItem, ElMessage, ElDialog } from 'element-plus'
import TableIndex from '@/components/table/index.vue'
import { projectTaskApi } from '@/api/project'
import { useRoute } from 'vue-router'
import { useStore } from "vuex"
import router from "@/router";
const state = reactive({
    tableData: [],
    changeList: [],
    centerDialogVisible: false,
    projectTendersWayList: [],
    implementationBehavior: [],
    page: {
        page: 1,
        pageSize: 10,
        total: 0
    },
    form: {
        taskName: '',
        planEndTime: '',
        planStartTime: '',
        responsibleDepartmentName: '',
        responsibleUserName: '',
        responsibleDepartmentId: ''
    }
})
const dialogRef = ref(null)
let formInline = reactive({
    itemName: '',
    planStartTime: [],
    responsibleUserId: '',
    actionId: '',
    responsibleDepartmentId: '',
    superviseUserId:''
})
const rules = {
    itemName: [
        { required: true, message: '(工作细项)名称不能为空', trigger: 'blur' }
    ],
    actionId: [
        { required: true, message: '对应实施行为不能为空', trigger: 'blur' }
    ],
    planStartTime: [
        { required: true, message: '实施期限不能为空', trigger: 'blur' }
    ]
}
// const tableData = reactive([])
const tableHead = reactive([
    {
        label: '工作细项(任务节点)',
        prop: 'itemName',
        minWidth: 150,
    },
    {
        label: '节点计划开始时间',
        prop: 'planStartTime',
        minWidth: 150,
    },
    {
        label: '节点计划结束时间',
        prop: 'planEndTime',
        minWidth: 150,
    },
    {
        label: '实施行为类型',
        prop: 'actionName',
        minWidth: 120,
    }
])
// let projectTendersWayList = reactive([])
const projectProposal = () => {
    state.centerDialogVisible = true
}
//表格数据批量上移
const upAllHandler = () => {
    if (state.changeList.length == 0) {
        ElMessage.warning('请选择需要上移的数据')
        return
    }
    let indexTaget = ''
    state.tableData.forEach((tableItem, i) => {
        state.changeList.forEach((item, index) => {
            if (item.itemId === tableItem.itemId) {
                indexTaget = i
            }
        })
    })
    upHandler(indexTaget)
}
const upHandler = (index) => {
    if (index == 0) {
        ElMessage.warning('已经是第一条数据了')
        return
    }
    const temp = state.tableData[index]
    state.tableData[index] = state.tableData[index - 1]
    state.tableData[index - 1] = temp
    sortUpdate()
}
//表格数据批量下移
const downAllHandler = () => {
    if (state.changeList.length == 0) {
        ElMessage.warning('请选择需要下移的数据')
        return
    }
    let indexTaget = ''
    state.tableData.forEach((tableItem, i) => {
        state.changeList.forEach((item, index) => {
            if (item.itemId === tableItem.itemId) {
                indexTaget = i
            }
        })
    })
    downHandler(indexTaget)
}
//表格数据下移动
const downHandler = (index) => {
    if (index == state.tableData.length - 1) {
        ElMessage.warning('已经是最后一条数据了')
        return
    }
    const temp = state.tableData[index]
    state.tableData[index] = state.tableData[index + 1]
    state.tableData[index + 1] = temp
    sortUpdate()
}
//选择复选框数据
const selectChange = (val) => {
    state.changeList = val
    // console.log(state.changeList);
}
//删除
const deleteHandler = () => {
    if (state.changeList.length == 0) {
        ElMessage.warning('请选择要删除的数据')
        return
    }
    projectTaskApi
        .delete({ itemIds: state.changeList.map((item) => item.itemId).join(',') })
        .then((res) => {
            if (res.code == '200') {
                ElMessage.success('操作成功')
                projectTaskList()
            }
        })
}

//保存配置
const saveConfigHandler = () => {
    projectTaskApi.sync(getProjectTaskId).then((res) => {
        if (res.code == '200') {
            ElMessage.success('操作成功')
            projectTaskList()
        }
    })
}
const formRef = ref(null)
//新增提交
const submitFormInline = () => {
    formRef.value.validate( (valid, fields) => {
        if (valid) {
            projectTaskApi
                .add({
                    planStartTime: formInline.planStartTime[0],
                    planEndTime: formInline.planStartTime[1],
                    itemName: formInline.itemName,
                    actionId: formInline.actionId,
                    responsibleDepartmentId: state.form.responsibleDepartmentId,
                    responsibleUserId: formInline.responsibleUserId,
                    projectTaskId: getProjectTaskId,
                    superviseUserId:formInline.superviseUserId
                })
                .then((res) => {
                    if (res.code == '200') {
                        state.centerDialogVisible = false
                        ElMessage.success('操作成功')
                        projectTaskList()
                        clearformInline()
                    }
                })
        }
    })
}
//清除表单
const clearformInline = () => {
    formInline.itemName = ''
    formInline.planStartTime = []
    formInline.responsibleUserId = ''
    formInline.actionId = ''
    formInline.responsibleDepartmentId = ''
}

const getProjectTaskId = router.currentRoute.value.params.projectTaskId;

let route = useRoute()
const getInfo = () => {
    projectTaskApi
        .getInfo(getProjectTaskId)
        .then((res) => {
            if (res.code == 200) {
                state.form = res.data
            }
        })
}
//更新排序
const sortUpdate = () => {
    projectTaskApi
        .sortUpdate({
            itemIds: state.tableData.map((item) => item.itemId).join(',')
        })
        .then((res) => {
            if (res.code == 200) {
                ElMessage.success('操作成功')
                projectTaskList()
            }
        })
}

let store = useStore();
const openDialog = () => {
    formInline.responsibleUserId = store.state.user.userId;
    getUserByDepartment(state.form.responsibleDepartmentId);
}

const closeDialog = () => {
    formInline = reactive({
        itemName: '',
        planStartTime: [],
        responsibleUserId: '',
        actionId: '',
        responsibleDepartmentId: ''
    })
}
//获取实施行为列表
const getBehavior = (isDark) => {
    if(isDark && parseInt(isDark) > 0){
        darkLine.taskList().then((res) => {
            if (res.code === '200') {
                state.implementationBehavior = res.data
            }
        })
    }else{
        projectTaskApi.behaviorList().then((res) => {
            if (res.code === '200') {
                state.implementationBehavior = res.data
            }
        })
    }
}

//获取列表
const projectTaskList = () => {
    projectTaskApi
        .projectTaskList(getProjectTaskId)
        .then((res) => {
            if (res.code == 200 && res.data) {
                state.tableData = res.data
            }
        })
}
//通过部门ID获取人员
const getUserByDepartment = (id) => {
    department.getUserByDepartmentId(id).then((res) => {
        state.projectTendersWayList = res?.data || []
    })
}

/**
 * 获取时间
 */
const getTime = () => {
    if(!state.form.planStartTime && !state.form.planEndTime){
        return `${ state.form.darkStartTime }至${ state.form.darkEndTime }`
    }
    if(state.form.planStartTime && state.form.planEndTime){
        return `${ state.form.planStartTime }至${ state.form.planEndTime }`
    }
}

onMounted(() => {
    getInfo()
    getBehavior(getURLhandler(route.path).isDark)
    projectTaskList()
})
</script>
<style scoped lang="scss">
.demo-form-inline {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.title {
    width: 100%;
}
.dialog {
    .el-form-item {
        width: 100% !important;
    }
}
.el-select {
    width: 100%;
}
</style>
<style lang="scss" scoped>
@import '@/views/constructionProjectManage/static/button.scss';
@import '@/views/constructionProjectManage/static/dialog.scss';
</style>
